package org.wx.io.netty.rpc.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.wx.io.netty.rpc.dispatcher.Dispatcher;
import org.wx.io.netty.rpc.protocol.MyContent;
import org.wx.io.netty.rpc.protocol.MyHeader;
import org.wx.io.netty.rpc.protocol.PackMsg;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: server 端的相应处理
 * @author: wangxun
 * @createDate: 2021/2/23
 * @version: 1.0
 */
@Slf4j
public class RpcServerHandler extends SimpleChannelInboundHandler<PackMsg> {

    static AtomicInteger num = new AtomicInteger();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PackMsg msg) throws Exception {

        log.info("RpcServerHandler 被调用了...{}",num.incrementAndGet());
        Dispatcher dispatcher = Dispatcher.getDispatcher();

        MyContent myContent = msg.getMyContent();
        Object o = dispatcher.get(myContent.getName());
        // 获取到请求对象
        if(o != null){

            Class<?> aClass = o.getClass();
            Method method = aClass.getMethod(myContent.getMethodName(), myContent.getParameterTypes());
            Object res = method.invoke(o, myContent.getParameters());

            MyHeader myHeader = msg.getMyHeader();
            // 设置返回的标记
            myHeader.setFlag(0X14141424);

            myContent.setRes(res);

        }else {
            // 为获取到请求对象，返回对应的错误码 0x99999999
            MyHeader myHeader = msg.getMyHeader();
            // 设置返回的标记
            myHeader.setFlag(0x99999999);
        }
        // 输出信息，调用编码器
        ctx.writeAndFlush(msg);
    }

}
